package com.attendance.utils.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 微信登录工具类
 *
 * @author 鵺丶
 * @date 2020/12/31
 */
public class WxUtil {
    private static final String APP_ID = "";
    private static final String SECRET = "";

    private WxUtil() {
    }

    /**
     * 获取微信资源访问令牌
     *
     * @param code 微信重定向携带得code值
     * @return {@link WxToken}* @throws Exception 异常
     */
    public static WxToken getAccessTokenUsCode(String code) throws Exception {
        JSONObject jsonObject = JSON.parseObject(getMethod(
                "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                        "appid=" + APP_ID +
                        "&secret=" + SECRET +
                        "&code=" + code +
                        "&grant_type=authorization_code"));
        try {
            WxToken wxToken = new WxToken();
            wxToken.setAccessToken(jsonObject.getString("access_token"));
            wxToken.setRefreshToken(jsonObject.getString("refresh_token"));
            wxToken.setRefreshToken(jsonObject.getString("openid"));
            return wxToken;
        } catch (Exception e) {
            throw new Exception("获取accessToken失败");
        }
    }

    /**
     * 刷新令牌
     *
     * @param wxToken 微信令牌集
     * @return {@link WxToken}* @throws Exception 异常
     */
    public static WxToken refreshToken(WxToken wxToken) throws Exception {
        JSONObject jsonObject = JSON.parseObject(getMethod(
                "https://api.weixin.qq.com/sns/oauth2/refresh_token?" +
                        "appid=" + APP_ID +
                        "&grant_type=refresh_token&" +
                        "refresh_token=" + wxToken.getRefreshToken()));
        try {
            wxToken.setAccessToken(jsonObject.getString("access_token"));
            wxToken.setRefreshToken(jsonObject.getString("refresh_token"));
            return wxToken;
        } catch (Exception e) {
            throw new Exception("刷新accessToken失败");
        }
    }

    /**
     * 获取微信用户资料
     *
     * @param wxToken 微信用户令牌集
     * @return {@link WxUser}* @throws Exception 异常
     */
    public static WxUser getWxUser(WxToken wxToken) throws Exception {
        JSONObject jsonObject = JSON.parseObject(getMethod(
                "https://api.weixin.qq.com/sns/userinfo?" +
                        "access_token=" + wxToken.getAccessToken() +
                        "&openid=" + wxToken.getOpenid()));
        try {
            WxUser wxUser = new WxUser();
            wxUser.setOpenid(jsonObject.getString("openid"));
            wxUser.setCountry(jsonObject.getString("country"));
            wxUser.setCity(jsonObject.getString("city"));
            wxUser.setNickname(jsonObject.getString("nickname"));
            wxUser.setHeadImageUrl(jsonObject.getString("headimgurl"));
            wxUser.setPrivilegeList(JSONArray.parseArray(jsonObject.getString("privilege"), String.class));
            wxUser.setSex(jsonObject.getString("sex"));
            wxUser.setUnionId(jsonObject.getString("unionid"));
            wxUser.setProvince(jsonObject.getString("province"));
            return wxUser;
        } catch (Exception e) {
            throw new Exception("获取用户资料失败");
        }
    }

    public static String getMethod(String url) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)
                .build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        throw new Exception("获取accessToken失败");
    }

}
